package com.online.questionnaire.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.online.questionnaire.common.R;
import com.online.questionnaire.common.ResultUtils;
import com.online.questionnaire.model.Surveys;
import com.online.questionnaire.model.dto.IndexInfo;
import com.online.questionnaire.service.SurveySubmitService;
import com.online.questionnaire.service.SurveysService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/index")
@Slf4j
@Tag(name = "首页信息接口")
public class IndexController {

    @Resource
    private SurveySubmitService surveySubmitService;
    @Resource
    private SurveysService surveysService;

    /**
     * 获取首页信息
     */
    @GetMapping("/info")
    public R<IndexInfo> getIndexInfo(){
        IndexInfo indexInfo = new IndexInfo();
        //查询提交数
        long count = surveySubmitService.count();
        indexInfo.setSubmitCount(count);
        //获取问卷数
        LambdaQueryWrapper<Surveys> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Surveys::getId);
        queryWrapper.eq(Surveys::getIsTemplate,0);
        indexInfo.setSurveyCount(surveysService.count(queryWrapper));
        //统计创建问卷的用户数量
        LambdaQueryWrapper<Surveys> userCountQuery = new LambdaQueryWrapper<>();
        userCountQuery.eq(Surveys::getIsTemplate, 0);
        // 只选择 createUserid 字段
        userCountQuery.select(Surveys::getCreateuserid);
        userCountQuery.groupBy(Surveys::getCreateuserid);

        // 使用自定义 SQL 查询用户数量
        long userCount = surveysService.list(userCountQuery).stream()
                .mapToInt(survey -> survey.getCreateuserid() != null ? 1 : 0)
                .sum();

        indexInfo.setUserCount(userCount);
        return ResultUtils.success(indexInfo);
    }


}
